package com.ng.exterauth.service.impl;

import java.util.Date;

import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ng.common.utils.TokenGenerator;
import com.ng.exterauth.dao.SysExterAppTokenDao;
import com.ng.exterauth.entity.SysExterAppTokenEntity;
import com.ng.exterauth.service.SysExterAppTokenService; 


@Service("sysExterAppTokenService")
public class SysExterAppTokenServiceImpl extends ServiceImpl<SysExterAppTokenDao, SysExterAppTokenEntity> implements SysExterAppTokenService {
	//12小时后过期
	private final static int EXPIRE = 3600 * 12;
	
	
	@Override
	public SysExterAppTokenEntity queryByToken(String token) {
		
		QueryWrapper<SysExterAppTokenEntity> query = new QueryWrapper<>();
		query.eq("token" , token);
		
		return getOne(query);
	}

	@Override
	public SysExterAppTokenEntity generateToken(String appId, String type) {

		//生成一个token
		String token = TokenGenerator.generateValue();

		//当前时间
		Date now = new Date();
		//过期时间
		Date expireTime = new Date(now.getTime() + EXPIRE * 1000);

		//判断是否生成过token
		SysExterAppTokenEntity tokenEntity = queryByAppAndType(appId , type);
		if(tokenEntity == null){
			tokenEntity = new SysExterAppTokenEntity();
			tokenEntity.setAppId(appId);
			tokenEntity.setToken(token);
			tokenEntity.setCreateTime(now);
			tokenEntity.setExpireTime(expireTime);

			//保存token
			this.save(tokenEntity);
		}else{
			tokenEntity.setToken(token);
			tokenEntity.setCreateTime(now);
			tokenEntity.setExpireTime(expireTime);

			//更新token
			this.updateById(tokenEntity);
		}

		return tokenEntity;
	}

	
	SysExterAppTokenEntity queryByAppAndType(String appId , String type) {
		QueryWrapper<SysExterAppTokenEntity> query = new QueryWrapper<>();
		query.eq("app_id", appId);
		query.eq("type", type != null && type.equals("pc") ? 1 : 0);
		
		
		return getOne(query);
		
	}

    

}
